package cn.edu.swu;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class TeacherDao {
    public void add(Teacher teacher) throws SQLException {
        QueryRunner queryRunner= new QueryRunner(PropertiesUtils.getDataSource());
        String sql = "insert into admin(Name,username,password) values(?,?,?)";
        queryRunner.update(sql,teacher.getName(),teacher.getUsername(),teacher.getPassword());
    }
    public void delete(Integer id) throws SQLException{
        QueryRunner queryRunner= new QueryRunner(PropertiesUtils.getDataSource());
        String sql = "delete from teacher where id=?";
        queryRunner.update(sql,id);
    }
    public void update(Teacher teacher) throws SQLException{
        QueryRunner queryRunner= new QueryRunner(PropertiesUtils.getDataSource());
        String sql = "update teacher set Name=?,password=? where id=?";
        queryRunner.update(sql,teacher.getName(),teacher.getPassword(),teacher.getId());
    }
    public List<Teacher> list(Teacher teacher) throws SQLException{
        QueryRunner queryRunner= new QueryRunner(PropertiesUtils.getDataSource());
        String sql = "select * from teacher";
        List<Teacher> list =queryRunner.query(sql,new BeanListHandler<>(Teacher.class));
        return list;
    }
    public Teacher findById(Integer id) throws SQLException {
        QueryRunner queryRunner= new QueryRunner(PropertiesUtils.getDataSource());
        String sql = "select * from teacher where id=?";
        Teacher teacher =queryRunner.query(sql,new BeanHandler<>(Teacher.class),id);
        return teacher;
    }
    public Teacher login(String username,String password) throws SQLException {
        QueryRunner queryRunner= new QueryRunner(PropertiesUtils.getDataSource());
        String sql = "select * from teacher where username=? and password=?";
        Teacher teacher =queryRunner.query(sql,new BeanHandler<>(Teacher.class),username,password);
        return teacher;
    }
}
